package com.itheima.marking_system.utils.aliyun;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;

@Component
public class OSSUtils {
    // TODO: 从配置文件中读取阿里云OSS相关配置。
    private static String endpoint = "https://oss-accelerate.aliyuncs.com";
    private static String accessKeyId = "LTAI5tDfQwKSbFNAv6vxdCQP";
    private static String accessKeySecret = "yTPMpX4oaepDa6PKuELl9IaM0W54Xa";
    private static String bucketName = "goudadadada";

    /**
     * 实现上传图片到OSS
     */
    public String upload(MultipartFile multipartFile) throws IOException {
        // 获取上传的文件的输入流
        InputStream inputStream = multipartFile.getInputStream();

        // 避免文件覆盖
        String originalFilename = multipartFile.getOriginalFilename();

        //上传文件到 OSS
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
        ossClient.putObject(bucketName, originalFilename, inputStream);

        //文件访问路径
        String url = "https://" + bucketName + "." + endpoint.split("//")[1] + "/" + originalFilename;

        // 关闭ossClient
        ossClient.shutdown();
        return url;// 把上传到oss的路径返回
    }

}
